require "Common/define"
require "Logic/Config"
require "Net/send_Msg"
require "Common/functions"

UIBagTreasure={}
HelperFunc.SetUIEnv(UIBagTreasure)
local this = UIBagTreasure;

this.LuaBehaviour = nil;
this.transform = nil;
this.gameObject = nil;
this.hasInit = false;
this.title = nil;
this.btn_back = nil;
this.chooseReward = nil;
this.details = nil;
this.probality = nil;
this.typeController = nil;

this.tabRewardGroup = {};
this.curData = nil;
this.rewardType = {
    details = 1,
    choose = 2,
    probality = 3,
}
this.Itype = rewardType.details;
this.tabItemData = {};
this.tabItem= {};
this.totalProbality = 0;
this.isHero = nil

function UIBagTreasure.Init(data,type)
    curData = data;
    Itype = type;
    local name, packageName = getUIName(PanelResNames.UIBagTreasure);
    panelMgr:ShowUI(name, packageName, this.OnCreate,Config.useLocalUI);
end

function UIBagTreasure.OnCreate(obj)
    if not hasInit then
        hasInit = true;
        btn_back = obj:GetChild("btn_back");
        typeController = obj:GetController("type")
        detailsDynamicList = obj:GetChild("detailsContent")

        chooseReward = obj:GetChild("UIBagChooseReward");
        chooseDynamicList = chooseReward:GetChild("content")
        useImage = chooseReward:GetChild("icon")
        useText = chooseReward:GetChild("Text")
        btn_use = chooseReward:GetChild("btn_use");
        probalityDynamicList = obj:GetChild("probalityContent")
        this.addEvent();
    end

    if typeController then
        typeController.selectedIndex = 0
    end
    this.initUI();
    tabItemData = {};
end

function UIBagTreasure.addEvent()
    btn_use.onClick:Add(this.sendReqUse);
    btn_back.onClick:Add(this.onClickBack);
end

function UIBagTreasure.removeEvent()
    btn_use.onClick:Remove(this.sendReqUse);
    btn_back.onClick:Remove(this.onClickBack);
end

function UIBagTreasure.OnDestroy()
    this.hasInit = false
    if this.touchAddTimer then
        utimer.remove(this.touchAddTimer)
        this.touchAddTimer = nil
    end
    if this.touchReduceTimer then
        utimer.remove(this.touchReduceTimer)
        this.touchReduceTimer = nil
    end
    this.removeEvent();
end

function UIBagTreasure.initUI()
    --拿奖励数据
    tabRewardGroup = {};
    local curId = curData["itemModelId"];
    local rewardData = G.dataTable["t_drop"];
    isHero = false
    for k,v in pairs(rewardData) do
        local id = v.f_DropPoolId;
        if tonumber(curId) == tonumber(id) then
            if v.f_Hero ~="" then
                table.insert(tabRewardGroup,v.f_Hero);
                isHero = true
            else
                table.insert(tabRewardGroup,v.f_Content)

            end
        end
    end
    local itemConfig = G.dataTable["t_item"];
    if Itype == rewardType.details then
        typeController.selectedIndex = 1
        local  Items = decodeJsonStrToTabel(tabRewardGroup[1]);
        detailsDynamicList:RemoveChildrenToPool()
        for i = 1, #Items do
            local itemModelId = tostring(Items[i][1]);
            if this.isAddItem(itemConfig, itemModelId) then
                local item = detailsDynamicList:AddItemFromPool()
                this.detailsSetData(item, Items[i]);
            end
        end
    elseif Itype == rewardType.choose then
        typeController.selectedIndex = 2
        useImage.url = EnumConst.AtlasPath.ItemAtlas..curData["icon"];
        useText.text = "0/"..curData["num"];
        tabItem = decodeJsonStrToTabel(tabRewardGroup[1]);
        chooseDynamicList:RemoveChildrenToPool()
        for i = 1, #tabItem do
            local itemModelId = tostring(tabItem[i][1]);
            if this.isAddItem(itemConfig, itemModelId) then
                local item = chooseDynamicList:AddItemFromPool()
                this.chooseSetData(item, tabItem[i]);
            end
        end
    elseif Itype == rewardType.probality then
        typeController.selectedIndex = 3
        local tabRewards = {};
        local tabAllItemData = {};
        for i = 1, #tabRewardGroup do
            local totalProbality = 0;
            local groupData = decodeJsonStrToTabel(tabRewardGroup[i]);
            for j = 1, #groupData do
                local itemModelId = tostring(groupData[j][1]);
                if this.isAddItem(itemConfig, itemModelId) then
                    totalProbality = totalProbality + groupData[j][3];
                end
            end
            local str = "[[0,"..i..","..totalProbality.."]]";
            if #this.tabRewardGroup > 1 then
                table.insert(tabRewards,str);
            else
                this.totalProbality = totalProbality
            end
            table.insert(tabRewards,tabRewardGroup[i]);
        end
        for i = 1, #tabRewards do
            local anGroupReward = decodeJsonStrToTabel(tabRewards[i]);
            for j = 1, #anGroupReward do
                local itemModelId = tostring(anGroupReward[j][1]);
                if this.isAddItem(itemConfig, itemModelId) then
                    table.insert(tabAllItemData,anGroupReward[j]);
                end
            end
        end
        print("==========概率展示==========>")
        probalityDynamicList:RemoveChildrenToPool()
        for i = 1, #tabAllItemData do
            local item = probalityDynamicList:AddItemFromPool()
            this.probalitySetData(item, tabAllItemData[i]);
        end
    end

end

function UIBagTreasure.isAddItem(itemConfig, itemModelId)
    local heroId = -1;
    if isHero then
        heroId = tonumber(itemModelId);
    else
        local itemCfg = itemConfig[tostring(itemModelId)];
        if itemCfg ~= nil then
            local bagType = tonumber(itemCfg.f_BagType);
            local localItemId = tonumber(itemCfg.f_itemModelId);
            if bagType == 32 then
                heroId = localItemId - 600000;
            elseif bagType == 4096 then
                heroId = localItemId - 201500;
            end
        end
    end
    if heroId < 0 or logicMgr.HeroManager.isHeroFullyOpen(heroId) then
        return true;
    end
    return false;
end

function UIBagTreasure.detailsSetData(itemGo,itemValue)
    local ctrlITem = CtrlManager.GetCtrl(PanelNames.Item);
    if ctrlITem ~= nil then
        local itemData = {};
        itemData["itemModelId"] = tostring(itemValue[1]);
        itemData["num"] = itemValue[2];
        if logicMgr.ItemManager.IsEquip(itemValue[1]) then
            local equipInfo = dataTable.getDataTableByStringId("t_equip",itemData["itemModelId"]);
            itemData["icon"] = equipInfo.f_EquipIcon;
            itemData["quality"] = equipInfo.f_EquipQuality;
        else
            local itemInfo = G.dataTable["t_item"][itemData["itemModelId"]];
            itemData["icon"] = itemInfo.f_Icon;
            itemData["quality"] = itemInfo.f_Quality;
        end
        ctrlITem.initData(itemGo,itemData);
    end
end

function UIBagTreasure.chooseSetData(itemGo, itemValue)
    local item = itemGo:GetChild("item");
    local btn_reduce = itemGo:GetChild("reduce");
    local btn_add = itemGo:GetChild("add");
    local btn_max = itemGo:GetChild("max");
    local numText = itemGo:GetChild("text")-- :GetComponent("TextMeshProUGUI");
    numText.text = 0;
    local ctrlItem = CtrlManager.GetCtrl(PanelNames.Item);
    local itemData = {};
    if ctrlItem ~= nil then
        itemData["itemModelId"] = tostring(itemValue[1]);
        itemData["num"] = itemValue[2];
        if logicMgr.ItemManager.IsEquip(itemValue[1]) then
            local equipInfo = dataTable.getDataTableByStringId("t_equip",itemData["itemModelId"]);
            itemData["icon"] = equipInfo.f_EquipIcon;
            itemData["quality"] = equipInfo.f_EquipQuality;
        else
            local itemInfo = G.dataTable["t_item"][itemData["itemModelId"]];
            itemData["icon"] = itemInfo.f_Icon;
            itemData["quality"] = itemInfo.f_Quality;
        end
        ctrlItem.initData(item,itemData);
    end
    this.computeUseNum(itemData,itemData["num"]);

    local num = 0;
    btn_reduce.onClick:Clear();
    btn_add.onClick:Clear();
    btn_max.onClick:Clear();
    btn_add.onTouchBegin:Clear();
    btn_add.onTouchEnd:Clear();
    btn_reduce.onTouchBegin:Clear();
    btn_reduce.onTouchEnd:Clear();
    btn_reduce.onClick:Add(function()
        num = num - 1;
        if num <= 0 then
            num = 0;
            numText.text = num;
            this.computeUseNum(itemData,num);
        else
            numText.text = num;
            this.computeUseNum(itemData,num);
        end
        local updateNum = this.computeChooseTotalNum();
        useText.text = updateNum.."/"..curData["num"];
    end);
    btn_add.onClick:Add(function()
        local chooseNum = this.computeChooseTotalNum();
        if chooseNum >= tonumber(curData["num"]) then
            return;
        else
            num = num + 1;
            numText.text = num;
            this.computeUseNum(itemData,num);
        end
        local updateNum = this.computeChooseTotalNum();
        useText.text = updateNum.."/"..curData["num"];
    end);
    btn_max.onClick:Add(function()
        local chooseNum = this.computeChooseTotalNum();
        if chooseNum >= curData["num"] then
            return;
        else
            local offset = curData["num"] - chooseNum;
            local curNum = numText.text;
            num = offset + tonumber(curNum);
            numText.text = num;
            this.computeUseNum(itemData,num);
        end
        local updateNum = this.computeChooseTotalNum();
        useText.text = updateNum.."/"..curData["num"];
    end);
    btn_add.onTouchBegin:Add(function()
        if this.touchAddTimer then
            utimer.remove(this.touchAddTimer)
            this.touchAddTimer = nil
        end
        this.touchAddTimer = utimer.delayCall(function ()
            local chooseNum = this.computeChooseTotalNum();
            if chooseNum >= curData["num"] then
                return;
            else
                local offset = curData["num"] - chooseNum;
                local curNum = numText.text;
                num = offset + tonumber(curNum);
                numText.text = num;
                this.computeUseNum(itemData,num);
            end
            local updateNum = this.computeChooseTotalNum();
            useText.text = updateNum.."/"..curData["num"];
        end, 1000)
    end);
    btn_add.onTouchEnd:Add(function()
        if this.touchAddTimer then
            utimer.remove(this.touchAddTimer)
            this.touchAddTimer = nil
        end
    end);

    btn_reduce.onTouchBegin:Add(function()
        if this.touchReduceTimer then
            utimer.remove(this.touchReduceTimer)
            this.touchReduceTimer = nil
        end
        this.touchReduceTimer = utimer.delayCall(function ()
            num = 0;
            numText.text = num;
            this.computeUseNum(itemData,num);
            local updateNum = this.computeChooseTotalNum();
            useText.text = updateNum.."/"..curData["num"];
        end, 1000)
    end);
    btn_reduce.onTouchEnd:Add(function()
        if this.touchReduceTimer then
            utimer.remove(this.touchReduceTimer)
            this.touchReduceTimer = nil
        end
    end);
end

function UIBagTreasure.probalitySetData(itemGo, itemValue)
    local title = itemGo:GetChild("title");
    local ttypeController = itemGo:GetController("type")
    ttypeController.selectedIndex = 0
    if tonumber(itemValue[1]) == 0 then
        ttypeController.selectedIndex = 2
        local titleText = itemGo:GetChild("text")
        titleText.text = "第"..tostring(itemValue[2]).."栏";
        totalProbality = itemValue[3];
    else
        ttypeController.selectedIndex = 1

        local name = itemGo:GetChild("name")
        local rate = itemGo:GetChild("rate")

        local itemConfig = G.dataTable["t_item"];
        local equipConfig = dataTable.getDataTable("t_equip");
        local heroConfig = G.dataTable["t_hero"]
        local itemModelId = tostring(itemValue[1]);
        local heroType = itemGo:GetController("herotype")
        if not isHero then
            heroType.selectedIndex = 0
            local item = itemGo:GetChild("item");
            local ctrlItem = CtrlManager.GetCtrl(PanelNames.Item);
            if ctrlItem ~= nil then
                local itemData = {};
                itemData["itemModelId"] = itemModelId;
                itemData["num"] = itemValue[2];
                if logicMgr.ItemManager.IsEquip(itemValue[1]) then
                    itemData["icon"] = equipConfig[itemModelId].f_EquipIcon;
                    itemData["quality"] = equipConfig[itemModelId].f_EquipQuality;
                else
                    itemData["icon"] = itemConfig[itemModelId].f_Icon;
                    itemData["quality"] = itemConfig[itemModelId].f_Quality;
                end
                ctrlItem.initData(item,itemData,nil,nil,true);
                name.text = getLanguage(itemConfig[itemModelId].f_ItemName);
            end
        else
            heroType.selectedIndex = 1
            local item = itemGo:GetChild("HeroItem");
            local itemData = {};
            itemData["icon"] = heroConfig[itemModelId].f_HeroIcon;
            itemData["quality"] = heroConfig[itemModelId].f_HeroInitialStar/10;
            local charactor = CtrlManager.GetCtrl(PanelNames.HeadRectItem);
            if charactor ~= nil then
                --初始英雄信息
                charactor.initData(item, itemData);
            end
            name.text = getLanguage(heroConfig[itemModelId].f_HeroName);
        end
        local probality = math.floor(tonumber(itemValue[3])/totalProbality *100000);
        --local num = math.floor(probality);
        --local num2 = math.floor(probality % 1 * 1000);
        --local num3;
        --if num2 == 0 then
        --    num3 = num .."%";
        --else
        --end
        --num3 = num * 0.001.."%";
        rate.text = (probality * 0.001).."%";
    end
end

function UIBagTreasure.computeUseNum(itemData,chooseNum)
    for i = 1, #tabItemData do
        if tabItemData[i]["itemModelId"] ~= nil and
                tonumber(tabItemData[i]["itemModelId"]) == tonumber(itemData["itemModelId"]) then
            tabItemData[i]["num"] = chooseNum;
            return;
        end
    end
    local item = {};
    item["itemModelId"] = itemData["itemModelId"];
    item["num"] = chooseNum;
    table.insert(tabItemData,item);
end

function UIBagTreasure.computeChooseTotalNum()
    local chooseTotalNum = 0;
    for i = 1, #tabItemData do
        chooseTotalNum = chooseTotalNum + tabItemData[i]["num"];
    end
    return chooseTotalNum;
end

function UIBagTreasure.sendReqUse()
    --选择了使用数量的奖励 tabItemData
    local needRemove = {};
    for i = 1, #tabItemData do
        if tabItemData[i]["num"] == 0 then
            table.insert(needRemove, tabItemData[i]["itemModelId"]);
        end
    end
    for rk, rv in pairs(needRemove) do
        for ik, iv in pairs(tabItemData) do
            if rv == iv["itemModelId"] then
                table.remove(tabItemData,ik);
                break;
            end
        end
    end
    if #tabItemData > 0 then
        local itemData = {};
        itemData["itemId"] = curData["itemId"];
        itemData["itemModelId"] = curData["itemModelId"];
        itemData["itemNum"] = this.computeChooseTotalNum();
        itemData["parameters"] = {};
        local para = {};
        for i = 1, #tabItemData do
            local tab = {};
            table.insert(tab,tonumber(tabItemData[i]["itemModelId"]));
            table.insert(tab,tonumber(tabItemData[i]["num"]));
            table.insert(para,tab);
        end
        local str = getJsonStr(para);
        table.insert(itemData["parameters"],str);
        itemHandler.sendReqUseItem(itemData);
        closeUI(PanelResNames.UIBagTreasure);
    else
        UISysTips.AddMsg("请选择要使用的奖励")
    end
end

function UIBagTreasure.onClickBack()
    closeUI(PanelResNames.UIBagTreasure);
end

return UIBagTreasure;